/*紫微斗数 Chinese Astrology Zi Wei Dou Shu*/
var ziweiUI = {
	//主星列印方向 true:由右向左,false:由左向右
	right2left:false,
	//UI resize
	resize:function (){
		//var wdth=$(window).width();
	  //$("#divZiWei").css("left",wdth>640?(wdth-640)/2:0);
	},
	genNowDateZiwei:function (){
		this.getNowDate();
		this.genZiwei();
	},
	getNowDate:function(){
		var Today=new Date();
		var h=Today.getHours();
		if(simpleLunarVars.setting.isLimit23H) Today.setDate(Today.getDate()+(h>=23?1:0));
		document.getElementById("txt_Year").value=Today.getFullYear();
		document.getElementById("sel_Month").value=Today.getMonth()+1;
		document.getElementById("sel_Day").value=Today.getDate();
		document.getElementById("sel_Hour").value=EarthlyBranches[(h+(h%2?1:0))%24/2];
	},
	//initial    	  
	initial:function (){
	  //画紫微斗数空表格
	  //document.getElementById("container").innerHTML="<div id='queryDiv'><h2>紫微斗数命盘</h2><div>阳历<select id='txt_Year'></select> 年<select id='sel_Month'></select> 月<select id='sel_Day'></select> 日<select id='sel_Hour'></select> 时<input type='radio' id='gender' name='gender' value='M' checked>男<input type='radio' name='gender' value='F'>女<input type='button' value='现在时间*' id='btnNowDate'></div></div><div class='ziwei'><div><div id='zw6'></div><div id='zw7'></div><div id='zw8'></div><div id='zw9'></div></div><div><div id='zw5'></div><div id='zw4'></div><div id='zwHome' class='zwDivCenter'></div><div id='zw10'></div><div id='zw11'></div></div><div><div id='zw3'></div><div id='zw2'></div><div id='zw1'></div><div id='zw12'></div></div></div>";
	  document.getElementById("container").innerHTML="<div class='zwDivHeader'><h2>紫微斗数命盘 </h2><div>阳历<input type='text' id='txt_Year' value='1990' />年<select id='sel_Month'></select> 月<select id='sel_Day'></select> 日<select id='sel_Hour'></select> 时<input type='radio' id='gender' name='gender' value='M' checked>男<input type='radio' name='gender' value='F'>女<input type='button' value='现在时间*' id='btnNowDate'></div></div><div class='ziwei'><div id='zw6'></div><div id='zw7'></div><div id='zw8'></div><div id='zw9'></div><div id='zw5'></div><div id='zwHome' class='zwDivCenter'></div><div id='zw10'></div><div id='zw4'></div><div id='zw11'></div><div id='zw3'></div><div id='zw2'></div><div id='zw1'></div><div id='zw12'></div></div>";
	  function addOption(id,a,b){
	  	for (i=a;i<=b;i++){ 
				let op = document.createElement('option');
	      op.value = i;
	      op.innerHTML = i;
	      document.getElementById(id).appendChild(op);
			}
	  }
	  //addOption("sel_Year",SIMPLE_MIN_YEAR,SIMPLE_MAX_YEAR);
	  addOption("sel_Month",1,12);
	  addOption("sel_Day",1,31);
	  for (i=0;i<EarthlyBranches.length;i++){ 
	  	let op = document.createElement('option');
	  	op.value = EarthlyBranches[i];
	    op.innerHTML = EarthlyBranches[i]+"【"+((24+(i*2-1))%24).toString()+"~"+ (i*2+1).toString()+"】";
	  	document.getElementById("sel_Hour").appendChild(op);
	  }
	  //初始日期
	  this.genNowDateZiwei();
	  this.resize();
	},
	clearPalce:function (){
		for (i=0;i<12;i++){ 
			document.getElementById("zw"+(i+1).toString()).innerHTML="<div class='MangA'>" +EarthlyBranches[i]+ "</div>";
		}
	},
	cleanZiwei:function (){
		//$("#zwHome").html(""); 
		document.getElementById("zwHome").innerHTML = "";
		this.clearPalce();
	},
	genZiwei:function(){
		let genderValue = getGenderValue();
		fillCartSetting();
		var zw = ziwei.computeZiWei( parseInt(document.getElementById("txt_Year").value), document.getElementById("sel_Month").value, document.getElementById("sel_Day").value, document.getElementById("sel_Hour").value, genderValue);
		document.getElementById("zwHome").innerHTML = "阳历：" + ziwei.getSolarDay() + "<br>"
					+ "农历(阴历)：" + ziwei.getLunarDay() + "<br>"
					+ "生肖：【" + ziwei.getShengXiao() + "】<span id='jzjr'>" + ziwei.getJiaZiDay() + "</span>日<br>"
					+ "<div>"+ ziwei.getFiveElement() +"</div>" 
					+ "<div>"+ ziwei.getYinYangGender()+"</div>"
					+ "<div class='zwcopy'>ahfrc.com</div>";
	  //render Direction
		var styleLR=[" zwStarLeft"," zwStarRight"];
		if(this.right2left){ styleLR.reverse(); }
		//render Star
	    for (i=0;i<12;i++){
	  		document.getElementById("zw"+(i+1).toString()).innerHTML+=    
	  				"<div class='MangA'>" + zw[i].MangA + "</div>" +
						"<div class='MangB'>" + zw[i].MangB + "</div>" +
						"<div class='MangC'>" + zw[i].MangC + "</div>" +
						"<div class='StarAll'>" + zw[i].StarAll + "</div>" ;
	  		var StarA1,StarA2,StarA3,StarB1,StarB2,StarC1,StarC2;
	  		StarA1="";StarA2="";StarA3="";StarB1="";StarB2="";StarC1="";StarC2="";
			var tmpSatrA=[[],[],[]];
			var k=0;
			for (j=0;j<zw[i].StarA.length;j++){
				tmpSatrA[0][k]=zw[i].StarA[j].substring(0,1);
	  			tmpSatrA[1][k]=zw[i].StarA[j].substring(1,2);
	  			tmpSatrA[2][k]=(zw[i].StarA[j].length>2)?"<span>"+zw[i].StarA[j].substring(3,4)+"</span>":"　";
				k+=1;
			}	
			for (j=0;j<zw[i].Star6.length;j++){
		  		tmpSatrA[0][k]="<span>"+zw[i].Star6[j].substring(0,1)+"</span>"
		  		tmpSatrA[1][k]="<span>"+zw[i].Star6[j].substring(1,2)+"</span>"
		  		tmpSatrA[2][k]=(zw[i].Star6[j].length>2)?"<span>"+zw[i].Star6[j].substring(3,4)+"</span>":"　";
				k+=1;
			}
			//style Left or Right
			if(this.right2left){
				for(j=0;j<3;j++){ tmpSatrA[j].reverse(); }
			}
			//render StarA & B & C
	  		for (j=0;j<tmpSatrA[0].length;j++){
				StarA1+=tmpSatrA[0][j];
	  			StarA2+=tmpSatrA[1][j];
	  			StarA3+=tmpSatrA[2][j];
	  		}
	  		for (j=0;j<zw[i].StarB.length;j++){
	  			StarB1+=zw[i].StarB[j].substring(0,1);
	  			StarB2+=zw[i].StarB[j].substring(1,2);
				}
	  		for (j=0;j<zw[i].StarC.length;j++){
	  			StarC1+=zw[i].StarC[j].substring(0,1);
	  			StarC2+=zw[i].StarC[j].substring(1,2);
		  	}
				document.getElementById("zw"+(i+1).toString()).innerHTML+=
						"<div class='StarA"+ styleLR[0] + "'>" + StarA1+ "<br>"+StarA2 + "<br><div class='Star4'>"+StarA3 + "</div></div>" +
	  				"<div class='StarB"+ styleLR[1] + "'>" + StarB1+ "<br>"+StarB2 + "</div>" +
	  				"<div class='StarC'>" + StarC1+ "<br>"+StarC2 + "</div>";
		}
		//大小限表
		var DS_Shian=ziwei.getDaShian();
		for (i=0;i<12;i++){
			document.getElementById("zw"+(i+1).toString()).innerHTML+=
					"<div class='MangY10'>"+ DS_Shian.DShian[i+1] + "</div>" +
					"<div class='MangY1'>" + DS_Shian.SShian[i+1] + "</div>" ;
		}
	}
};

/**
 * 取性别值
 * @returns {string}
 */
function getGenderValue() {
	let genderValue="M";
	let gender=	document.querySelectorAll("input[type=radio]");
	for (i=0;i<gender.length;i++){
		if (gender[i].checked){
			genderValue=gender[i].value;
			break;
		}
	}
	return genderValue;
}

/**
 * 设定排盘设置
 * @return {number} 设置项数量
 */
function fillCartSetting() {
	simpleLunarVars.setting.isYueJie = false;//是否依月节来判定月份
	simpleLunarVars.setting.isLimit23H = false;//日的分界点是否为23:00
	let yjchk = document.getElementById("yue_jie");
	if(typeof yjchk !== 'undefined' && yjchk.checked == false){
		simpleLunarVars.setting.isYueJie = true;
	}
	let h23chk = document.getElementById("day_23L");
	if(typeof h23chk !== 'undefined' && h23chk.checked == false){
		simpleLunarVars.setting.isLimit23H = true;
	}
	return Object.keys(simpleLunarVars.setting).length;
}
/**
 * 批量读取表格数据
 * @param {string} data 数据
 * @param {string} chr 分隔符
 * @returns {*[]}
 */
function readExcelRows(data, chr="\t") {
	var ret = [];
	if (!chr) {
		let g1x = data.match(/\t/g);
		let g2x = data.match(/,/g);
		let g3x = data.match(/;/g);
		g1x = g1x ? g1x.length : 0;
		g2x = g2x ? g2x.length : 0;
		g3x = g3x ? g3x.length : 0;
		chr = "\t";
		if (g1x < 6) {
			if (g2x >= g1x * 2) {
				chr = ",";
				if (g3x > g2x) {
					chr = ";";
				}
			}
		}
	}
	var allRows = data.split(/[\r\n]+/g);
	for (var sr = 0; sr < allRows.length; sr++) {
		if (allRows[sr].replace(/(^\s+)|(\s+$)/g, "").length > 0) {
			var rowCells = allRows[sr].split(chr);
			ret.push(rowCells);
		}
	}
	return ret;
};

/**
 * 格式化日期时间
 * @param {string} sDate
 * @returns {Object|boolean}
 */
function getDatefromStr(sDate) {
	var px = sDate.match(/(?<Y>\-?\d{4})[\D]*(?<M>\d{1,2})[\D]*(?<D>\d{1,2})([\D]*(?<h>\d{1,2})[\D]*(?<m>\d{1,2})?[\D]*(?<s>[\d.]+)?)?/);
	if (px) {
		let The = new Object();
		The.Y = parseInt(px.groups.Y);
		The.M = parseInt(px.groups.M);
		The.D = parseInt(px.groups.D);
		The.h = The.m = The.s = 0;
		if (typeof px.groups.h !== 'undefined')
			The.h = parseInt(px.groups.h);
		if (typeof px.groups.m !== 'undefined')
			The.m = parseInt(px.groups.m);
		if (typeof px.groups.s !== 'undefined')
			The.s = parseFloat(px.groups.s);
		The.Hour = ((The.s / 60 + The.m) / 60 + The.h) / 24;
		return The;
	}
	return false;
};

/**
 * 批量计算紫微星
 * @param handler
 * @param {string} split_chr
 * @returns {number|boolean}
 */
function batchComputeZiWei(handler,split_chr="\t") {
	let retv = false;
	if(!handler || !handler.value){
		handler= document.getElementById('timeList');
		if(!handler.value) return retv;
	}
	let drows = handler.value;
	let rows = readExcelRows(drows, split_chr);
	let arr = [];
	let i = 0;
	if (rows.length > 0) {
		if(rows.length == 1 && rows[0][0].indexOf('~') > 0){
			let timeLines = rows[0][0].split(/\s*[~,;]\s*/);
			let d1 = new Date(timeLines[0].trim());
			let d2 = new Date(timeLines[1].trim());
			let addHV = 2;
			let reg = /^\s*(\+|\-)?[0-9]+(\.?[0-9]+)?\s*$/;
			if(timeLines.length > 2 && reg.test(timeLines[2])){
				addHV = parseInt(timeLines[2].trim());
			}
			//let timezoneOf = (new Date().getTimezoneOffset() / 60).toString();
			rows = [];
			let lastHours = d1.getHours() - (addHV % 24);
			let lastDate = d1.getDate() - int2(addHV / 24);
			if(lastHours < 0) {
				lastHours += 24;
				lastDate--;
			}
			if(lastDate < 0) lastDate++;
			let adday = int2(addHV / 24);
			for (; d1 < d2; d1.setHours(d1.getHours()+addHV)) {
				let dstr = d1.toLocaleString();
				let ghi = d1.getHours() - lastHours;
				if(ghi < 0){
					ghi += 24;
				}
				let hx = ghi + adday * 24;
				if(hx != addHV){ //防止夏令时
					let curM = d1.getMonth();
					let curD = d1.getDate() + adday;
					let curH = d1.getHours() - hx + (addHV % 24);
					if(curH < 0){
						curH += 24;
						curD -= 1;
						if(curD <= 0){
							curM -= 1;
							let dt1 = new Date(d1.getFullYear(),curM,curD - 1);
							curD = dt1.getDate();
						}
					}
					curM++;
					dstr = d1.getFullYear().toString() + "/" + curM + "/" + curD + " " + curH + ":" + d1.getMinutes() + ":" + d1.getSeconds();
					lastDate =curM;
					lastHours = curH;
				}
				else{
					lastDate = d1.getDate();
					lastHours = d1.getHours();
				}
				rows.push([dstr]);
			}
			rows.push([d2.toLocaleString()]);
		}
		else{
			if (getDatefromStr(rows[0][0]) == false) {
				i = 1;
			}
		}
	}
	let genderValue = getGenderValue();
	fillCartSetting();
	let oks = 0;
	for (; i < rows.length; i++){
		let dv = getDatefromStr(rows[i][0]);
		if(dv){
			if(simpleLunarVars.setting.isLimit23H && dv.h == 23){//夜子时,日期加+
				if(dv.D < 27){
					dv.D++;
				}
				else
				{
					let milliseconds = (new Date(dv.Y,dv.M-1,dv.D,dv.h,dv.m,dv.s)).valueOf();
					let dv2 = getDatefromStr(new Date(milliseconds+3600000).toLocaleString());
					dv.Y = dv2.Y;
					dv.M = dv2.M;
					dv.D = dv2.D;
				}
			}
			let zw = ziwei.computeZiWei(dv.Y.toString(),dv.M.toString(),dv.D.toString(),HourChen[dv.h],genderValue,false);
			arr.push(rows[i][0]+"\t"+ziwei.getLunarDay()+"\t"+ziwei.f+"\t"+ziwei.l+"\t"+ziwei.z);
			oks++;
		}
	}
	if(oks > 0){
		arr.unshift("阳历\t农历\t五行局\t命宫\t紫微星");
	}
	handler.value = arr.join("\r\n");
	return oks;
}

/****************
 地理经纬度选择的页面控制函数
 ****************/
function change2(){
	var i,v = new JWdecode( Sel2.options[Sel2.selectedIndex].value );
	Sel2.vJ = v.J; Sel2.vW = v.W;
	Cb_J.value=(v.J/Math.PI*180).toFixed(6), Cb_W.value=(v.W/Math.PI*180).toFixed(6);
	Cal_zdzb.innerHTML = '经 '+rad2str2(v.J) + ' 纬 '+rad2str2(v.W);
	//showMessD(-2);
	storageL.setItem('Sel1',Sel1.selectedIndex,1000);
	storageL.setItem('Sel2',Sel2.selectedIndex,1000);

}
function change(){
	Sel2.length=0;
	var i, ob=JWv[ Sel1.options[Sel1.selectedIndex].value-0 ];
	for(i=1; i<ob.length; i++)
		addOp( Sel2, ob[i].substr(0,4), ob[i].substr(4,ob[i].length-4) );
	change2();
}

window.addEventListener('load' ,function(){
	//加载地址数据:
	let i=0;
	for(;i<JWv.length;i++) addOp(document.all.Sel1,i,JWv[i][0]);

	let seI1 = storageL.getItem('Sel1');
	let seI2 = storageL.getItem('Sel2');
	let sel1Hander = document.getElementById("Sel1");
	let sel2Hander = document.getElementById("Sel2");
	sel1Hander.selectedIndex = seI1; change();
	sel2Hander.selectedIndex = seI2; change2();
//开始使用
	ziweiUI.initial();
	document.getElementById("btnNowDate").addEventListener('click',function () {ziweiUI.genNowDateZiwei();});
	let r = document.getElementsByName('gender');
	let rs = [];
	for (let i=0;i<r.length;i++){
		rs.push(r[i]);
	}
	rs.push(document.getElementById("sel_Day"));
	rs.push(document.getElementById("sel_Hour"));
	rs.push(document.getElementById("yue_jie"));
	rs.push(document.getElementById("day_23L"));
	for (let i=0;i<rs.length;i++){
		if(rs[i]) rs[i].addEventListener('change',function () {ziweiUI.genZiwei();});
	}
	window.addEventListener('resize',function() { ziweiUI.resize();});
	//$(window).resize(function() { ziweiUI.resize();});
});